<template>
  <div>
    <el-form inline :model="formModel">
      <el-form-item label="起点">
        <el-input v-model="formModel.startValue" />
      </el-form-item>

      <el-form-item label="终点">
        <el-input v-model="formModel.endValue" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handle">规划路径</el-button>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="markers.length !== 2" @click="handleTwo">规划路径Two</el-button>
      </el-form-item>
    </el-form>

    <div ref="boxRef" class="box"></div>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 支持 WebserverApi 的key,最好不要我们前端来调用，在公司里面，更多的是后端会包装一层接口给我们
const key = 'EBEBZ-2LHCZ-WLSXQ-TPDO3-M6XLV-TNF6A'
const boxRef = ref<HTMLDivElement | null>(null)
let map: any = null

const markers = ref<any[]>([])

const formModel = reactive({
  startValue: '广东省深圳市宝安区后瑞地铁站A口',
  endValue: '广东省深圳市宝安区西乡天虹购物广场'
})

async function initMap(cb?: (map: any) => void) {
  const { data } = await axios.get('/map/ws/location/v1/ip', {
    params: {
      key
    }
  })

  map = new TMap.Map(boxRef.value, {
    center: [data.result.location.lat, data.result.location.lng] // 中心点经纬度
  })

  // 执行回调函数 cb
  cb && cb(map)
}

// 地址解析
async function getCoder(text: string) {
  const { data } = await axios('/map/ws/geocoder/v1/', {
    params: {
      key,
      address: text
    }
  })
  const { status, message, result } = data

  if (status !== 0) {
    ElMessage.warning(message)
    return Promise.reject(message)
  }

  return result.location
}

// 驾车路线规划
async function driving(from: { lat: number; lng: number }, to: { lat: number; lng: number }) {
  const { data } = await axios.get('/map/ws/direction/v1/driving/', {
    params: {
      from: `${from.lat},${from.lng}`,
      to: `${to.lat},${to.lng}`,
      key
    }
  })

  const pl = []
  // 坐标点的解压
  let coors = data.result.routes[0].polyline
  for (let i = 2; i < coors.length; i++) {
    coors[i] = coors[i - 2] + coors[i] / 1000000
  }

  //将解压后的坐标生成LatLng数组
  for (let i = 0; i < coors.length; i += 2) {
    pl.push(new TMap.LatLng(coors[i], coors[i + 1]))
  }

  return pl
}

// 开始规划
async function handle() {
  const startLocation = await getCoder(formModel.startValue)
  const endLocation = await getCoder(formModel.endValue)

  const data = await driving(startLocation, endLocation)

  new TMap.MultiPolyline({
    map,
    styles: {
      hello: new TMap.PolylineStyle({
        color: '#3777FF',
        width: 10
      })
    },
    geometries: [
      {
        id: 1,
        styleId: 'hello',
        paths: data
      }
    ]
  })
}

// 给地图添加点击事件
function addMapClickListener(map: any) {
  // 1. 创建出 Marker 图层
  const marker = new TMap.MultiMarker({ map })

  map.on('click', (e: any) => {
    // 判断当前 markers.length 的长度
    if (markers.value.length === 2) {
      // 修改下标为0的这一项
      markers.value[0] = e.latLng
      marker.updateGeometries([
        {
          id: 'from',
          position: e.latLng
        }
      ])
    } else {
      markers.value.push(e.latLng)
      marker.add([
        {
          id: markers.value.length === 1 ? 'from' : 'to',
          position: e.latLng
        }
      ])
    }
  })
}

async function handleTwo() {
  const data = await driving(markers.value[0], markers.value[1])
  new TMap.MultiPolyline({
    map,
    styles: {
      hello: new TMap.PolylineStyle({
        color: '#3777FF',
        width: 10
      })
    },
    geometries: [
      {
        id: 1,
        styleId: 'hello',
        paths: data
      }
    ]
  })
}

onMounted(() => {
  initMap(addMapClickListener)
})
</script>

<style lang="scss" scoped></style>
